<template>
  <div class="agent-chat-container">
    123
    123
    <!-- 头部 -->
    <div class="chat-header">
      <div class="header-left">
        <div class="robot-icon">🤖</div>
        <div class="header-info">
          <h1 class="header-title">Boss智能招聘助手</h1>
          <div class="status-indicator">
            <span class="status-dot" :class="{ online: isOnline }"></span>
            <span class="status-text">{{ isOnline ? '在线' : '离线' }}</span>
          </div>
        </div>
      </div>
      <div class="header-right">
        <button class="header-btn" @click="toggleTools" title="查看工具">
          <span class="btn-icon">🛠️</span>
          <span class="btn-text">工具</span>
        </button>
        <button class="header-btn" @click="handleClearChat" title="清空对话">
          <span class="btn-icon">🗑️</span>
          <span class="btn-text">清空</span>
        </button>
      </div>
    </div>

    <!-- 工具面板 -->
    <transition name="slide-down">
      <div v-if="showTools" class="tools-panel">
        <div class="tools-header">
          <h3>可用工具 ({{ tools.length }})</h3>
          <button class="close-btn" @click="toggleTools">✕</button>
        </div>
        <div v-if="toolsLoading" class="tools-loading">
          <div class="loading-spinner"></div>
          <span>加载中...</span>
        </div>
        <div v-else-if="tools.length > 0" class="tools-grid">
          <div 
            v-for="(tool, index) in tools" 
            :key="index" 
            class="tool-card"
          >
            <div class="tool-icon">⚙️</div>
            <div class="tool-name">{{ formatToolName(tool.name) }}</div>
            <div class="tool-description">{{ tool.description }}</div>
          </div>
        </div>
        <div v-else class="tools-empty">
          暂无可用工具
        </div>
      </div>
    </transition>

    <!-- 错误提示 -->
    <transition name="fade">
      <div v-if="error" class="error-banner">
        <span class="error-icon">⚠️</span>
        <span class="error-text">{{ error }}</span>
        <button class="error-close" @click="clearError">✕</button>
      </div>
    </transition>

    <!-- 消息区域 -->
    <div class="messages-container" ref="messagesContainer">
      <!-- 欢迎页面 -->
      <div v-if="messages.length === 0" class="welcome-screen">
        <div class="welcome-icon">👋</div>
        <h2 class="welcome-title">欢迎使用Boss智能招聘助手</h2>
        <p class="welcome-subtitle">我可以帮助您进行招聘相关的工作，请选择或输入您的问题</p>
        <div class="quick-questions">
          <button 
            v-for="(question, index) in exampleQuestions" 
            :key="index"
            class="quick-question-btn"
            @click="handleQuickQuestion(question)"
          >
            {{ question }}
          </button>
        </div>
      </div>

      <!-- 消息列表 -->
      <div v-else class="messages-list">
        <div 
          v-for="(message, index) in messages" 
          :key="index"
          class="message-wrapper"
          :class="message.role"
        >
          <div class="message-avatar">
            <span v-if="message.role === 'user'">👤</span>
            <span v-else>🤖</span>
          </div>
          <div class="message-content">
            <div class="message-header">
              <span class="message-sender">
                {{ message.role === 'user' ? '您' : 'Boss助手' }}
              </span>
              <span class="message-time">{{ message.time }}</span>
            </div>
            <div class="message-text" v-html="formatMessage(message.content)"></div>
            <div v-if="message.toolCalls > 0" class="tool-calls-badge">
              <span class="badge-icon">🛠️</span>
              <span>使用了 {{ message.toolCalls }} 个工具</span>
            </div>
          </div>
        </div>

        <!-- 加载动画 -->
        <div v-if="isLoading" class="message-wrapper assistant loading">
          <div class="message-avatar">
            <span>🤖</span>
          </div>
          <div class="message-content">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <div class="input-wrapper">
        <textarea
          ref="textareaRef"
          v-model="userInput"
          class="input-field"
          placeholder="输入您的问题..."
          rows="1"
          @input="autoResize"
          @keydown.enter.exact.prevent="sendMessage"
          @keydown.enter.shift.exact="handleShiftEnter"
          :disabled="isLoading"
        ></textarea>
        <button 
          class="send-btn"
          @click="sendMessage"
          :disabled="!userInput.trim() || isLoading"
        >
          <span v-if="isLoading" class="loading-spinner-small"></span>
          <span v-else>发送 →</span>
        </button>
      </div>
      <div class="input-hint">
        💡 提示：您可以问我关于招聘的任何问题。按 Enter 发送，Shift + Enter 换行
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, nextTick, onMounted, watch } from 'vue'
import { sendMessageToAgent, getAgentTools, clearAgentMemory } from '@/utils/agentApi.js'

export default {
  name: 'AgentChatView',
  setup() {
    // 状态管理
    const userId = ref(1) // TODO: 从登录信息获取
    const sessionId = ref(null)
    const messages = ref([])
    const userInput = ref('')
    const isLoading = ref(false)
    const error = ref(null)
    const showTools = ref(false)
    const isOnline = ref(true)
    const tools = ref([])
    const toolsLoading = ref(false)
    
    // DOM引用
    const messagesContainer = ref(null)
    const textareaRef = ref(null)
    
    // 快捷问题
    const exampleQuestions = [
      '帮我查询Python工程师职位',
      '推荐适合的候选人',
      '公司有什么福利？',
      '分析本月招聘数据'
    ]

    // 初始化会话ID
    const initSessionId = () => {
      let sid = sessionStorage.getItem('boss_agent_session_id')
      if (!sid) {
        sid = 'sess_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
        sessionStorage.setItem('boss_agent_session_id', sid)
      }
      sessionId.value = sid
    }

    // 获取当前时间
    const getCurrentTime = () => {
      const now = new Date()
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      return `${hours}:${minutes}`
    }

    // 格式化消息内容（支持简单Markdown）
    const formatMessage = (content) => {
      let html = content
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
      
      // 换行
      html = html.replace(/\n/g, '<br>')
      
      // 加粗 **text**
      html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
      
      // 数字序列
      html = html.replace(/^(\d+\.\s)/gm, '<strong>$1</strong>')
      
      return html
    }

    // 格式化工具名称
    const formatToolName = (name) => {
      return name
        .replace(/_/g, ' ')
        .replace(/tool/gi, '')
        .trim()
        .split(' ')
        .map(word => word.charAt(0).toUpperCase() + word.slice(1))
        .join(' ')
    }

    // 自动滚动到底部
    const scrollToBottom = () => {
      nextTick(() => {
        if (messagesContainer.value) {
          messagesContainer.value.scrollTo({
            top: messagesContainer.value.scrollHeight,
            behavior: 'smooth'
          })
        }
      })
    }

    // Textarea自适应高度
    const autoResize = () => {
      nextTick(() => {
        const textarea = textareaRef.value
        if (textarea) {
          textarea.style.height = 'auto'
          const newHeight = Math.min(textarea.scrollHeight, 150)
          textarea.style.height = newHeight + 'px'
        }
      })
    }

    // 处理Shift+Enter
    const handleShiftEnter = (e) => {
      // 允许默认换行行为
    }

    // 显示错误
    const showError = (message) => {
      error.value = message
      setTimeout(() => {
        error.value = null
      }, 5000)
    }

    // 清除错误
    const clearError = () => {
      error.value = null
    }

    // 发送消息
    const sendMessage = async () => {
      const message = userInput.value.trim()
      
      // 验证输入
      if (!message) {
        showError('请输入消息内容')
        return
      }
      
      if (isLoading.value) {
        return
      }
      
      if (message.length > 1000) {
        showError('消息长度不能超过1000字')
        return
      }
      
      // 添加用户消息
      messages.value.push({
        role: 'user',
        content: message,
        time: getCurrentTime(),
        toolCalls: 0
      })
      
      // 清空输入框
      userInput.value = ''
      autoResize()
      
      // 滚动到底部
      scrollToBottom()
      
      // 设置加载状态
      isLoading.value = true
      
      try {
        // 调用API
        const response = await sendMessageToAgent(
          userId.value,
          message,
          sessionId.value
        )
        
        if (response.data.code === 200) {
          // 添加AI回复
          messages.value.push({
            role: 'assistant',
            content: response.data.data.output,
            time: getCurrentTime(),
            toolCalls: response.data.data.tool_calls || 0
          })
          
          // 更新sessionId
          if (response.data.data.session_id) {
            sessionId.value = response.data.data.session_id
            sessionStorage.setItem('boss_agent_session_id', sessionId.value)
          }
          
          // 滚动到底部
          scrollToBottom()
        } else {
          showError(response.data.msg || '发送失败')
        }
      } catch (err) {
        console.error('发送消息失败:', err)
        
        if (!err.response) {
          showError('网络连接失败，请检查网络')
        } else if (err.code === 'ECONNABORTED') {
          showError('请求超时，请重试')
        } else {
          const msg = err.response?.data?.msg || '发送失败，请重试'
          showError(msg)
        }
      } finally {
        isLoading.value = false
      }
    }

    // 处理快捷问题
    const handleQuickQuestion = (question) => {
      userInput.value = question
      sendMessage()
    }

    // 切换工具面板
    const toggleTools = () => {
      showTools.value = !showTools.value
      if (showTools.value && tools.value.length === 0) {
        loadTools()
      }
    }

    // 加载工具列表
    const loadTools = async () => {
      toolsLoading.value = true
      try {
        const response = await getAgentTools()
        if (response.data.code === 200) {
          tools.value = response.data.data.tools || []
        } else {
          showError('加载工具列表失败')
        }
      } catch (err) {
        console.error('加载工具失败:', err)
        showError('加载工具列表失败')
      } finally {
        toolsLoading.value = false
      }
    }

    // 清空对话
    const handleClearChat = async () => {
      if (messages.value.length === 0) {
        return
      }
      
      if (!confirm('确定要清空对话吗？此操作不可恢复。')) {
        return
      }
      
      try {
        // 调用清除记忆API
        await clearAgentMemory(userId.value, sessionId.value)
        
        // 清空消息列表
        messages.value = []
        
        // 重置会话ID
        const newSessionId = 'sess_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
        sessionId.value = newSessionId
        sessionStorage.setItem('boss_agent_session_id', newSessionId)
        
      } catch (err) {
        console.error('清空对话失败:', err)
        showError('清空对话失败')
      }
    }

    // 组件挂载时初始化
    onMounted(() => {
      initSessionId()
      // 预加载工具列表
      loadTools()
    })

    return {
      // 状态
      userId,
      sessionId,
      messages,
      userInput,
      isLoading,
      error,
      showTools,
      isOnline,
      tools,
      toolsLoading,
      exampleQuestions,
      
      // DOM引用
      messagesContainer,
      textareaRef,
      
      // 方法
      formatMessage,
      formatToolName,
      scrollToBottom,
      autoResize,
      handleShiftEnter,
      showError,
      clearError,
      sendMessage,
      handleQuickQuestion,
      toggleTools,
      handleClearChat
    }
  }
}
</script>

<style scoped>
/* ==================== 全局样式 ==================== */
.agent-chat-container {
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 80px);
  height: calc(100vh - 80px);
  background: #f5f7fa;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  margin-top: 0;
}

/* ==================== 头部样式 ==================== */
.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.robot-icon {
  font-size: 40px;
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

.header-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.header-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ccc;
  animation: pulse 2s infinite;
}

.status-dot.online {
  background: #00ff88;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

.status-text {
  opacity: 0.9;
}

.header-right {
  display: flex;
  gap: 10px;
}

.header-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 8px;
  color: white;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.header-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
}

.btn-icon {
  font-size: 16px;
}

/* ==================== 工具面板 ==================== */
.tools-panel {
  background: white;
  border-bottom: 1px solid #e5e7eb;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  max-height: 400px;
  overflow-y: auto;
}

.tools-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  border-bottom: 1px solid #e5e7eb;
}

.tools-header h3 {
  margin: 0;
  font-size: 18px;
  color: #1f2937;
}

.close-btn {
  width: 30px;
  height: 30px;
  border: none;
  background: #f3f4f6;
  border-radius: 50%;
  cursor: pointer;
  font-size: 18px;
  color: #6b7280;
  transition: all 0.2s;
}

.close-btn:hover {
  background: #e5e7eb;
  transform: rotate(90deg);
}

.tools-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 40px;
  color: #6b7280;
}

.tools-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 15px;
  padding: 20px 30px;
}

.tool-card {
  padding: 20px;
  background: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  transition: all 0.3s;
  cursor: pointer;
}

.tool-card:hover {
  background: white;
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
  transform: translateY(-2px);
}

.tool-icon {
  font-size: 24px;
  margin-bottom: 10px;
}

.tool-name {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 8px;
}

.tool-description {
  font-size: 14px;
  color: #6b7280;
  line-height: 1.5;
}

.tools-empty {
  padding: 40px;
  text-align: center;
  color: #9ca3af;
}

/* ==================== 错误提示 ==================== */
.error-banner {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 15px 30px;
  background: #fee2e2;
  border-bottom: 2px solid #ef4444;
  color: #991b1b;
  font-size: 14px;
  z-index: 20;
}

.error-icon {
  font-size: 20px;
}

.error-text {
  flex: 1;
}

.error-close {
  width: 24px;
  height: 24px;
  border: none;
  background: transparent;
  cursor: pointer;
  font-size: 18px;
  color: #991b1b;
  transition: opacity 0.2s;
}

.error-close:hover {
  opacity: 0.7;
}

/* ==================== 消息区域 ==================== */
.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 30px;
}

/* 欢迎页面 */
.welcome-screen {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
}

.welcome-icon {
  font-size: 80px;
  margin-bottom: 20px;
  animation: wave 2s ease-in-out infinite;
}

@keyframes wave {
  0%, 100% {
    transform: rotate(0deg);
  }
  25% {
    transform: rotate(20deg);
  }
  75% {
    transform: rotate(-20deg);
  }
}

.welcome-title {
  font-size: 32px;
  font-weight: 700;
  color: #1f2937;
  margin: 0 0 10px 0;
}

.welcome-subtitle {
  font-size: 16px;
  color: #6b7280;
  margin: 0 0 40px 0;
}

.quick-questions {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  max-width: 600px;
}

.quick-question-btn {
  padding: 15px 25px;
  background: white;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  font-size: 14px;
  color: #374151;
  cursor: pointer;
  transition: all 0.3s;
  text-align: left;
}

.quick-question-btn:hover {
  border-color: #667eea;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

/* 消息列表 */
.messages-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.message-wrapper {
  display: flex;
  gap: 15px;
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-wrapper.user {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  flex-shrink: 0;
}

.message-wrapper.user .message-avatar {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.message-content {
  max-width: 70%;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.message-header {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 13px;
}

.message-sender {
  font-weight: 600;
  color: #374151;
}

.message-time {
  color: #9ca3af;
}

.message-text {
  padding: 15px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  line-height: 1.6;
  color: #1f2937;
  word-wrap: break-word;
}

.message-wrapper.user .message-text {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.tool-calls-badge {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  background: #f0fdf4;
  border: 1px solid #86efac;
  border-radius: 20px;
  font-size: 12px;
  color: #15803d;
  width: fit-content;
}

.badge-icon {
  font-size: 14px;
}

/* 加载动画 */
.typing-indicator {
  display: flex;
  gap: 6px;
  padding: 15px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background: #9ca3af;
  border-radius: 50%;
  animation: typing 1.4s infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-10px);
  }
}

/* ==================== 输入区域 ==================== */
.input-area {
  padding: 20px 30px 30px;
  background: white;
  border-top: 1px solid #e5e7eb;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.input-wrapper {
  display: flex;
  gap: 15px;
  align-items: flex-end;
  max-width: 1000px;
  margin: 0 auto;
}

.input-field {
  flex: 1;
  padding: 15px 20px;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  font-size: 15px;
  font-family: inherit;
  resize: none;
  transition: all 0.3s;
  min-height: 52px;
  max-height: 150px;
}

.input-field:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.input-field:disabled {
  background: #f9fafb;
  cursor: not-allowed;
}

.send-btn {
  padding: 15px 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 12px;
  color: white;
  font-size: 15px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  min-width: 100px;
  height: 52px;
}

.send-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.send-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
}

.input-hint {
  margin-top: 15px;
  text-align: center;
  font-size: 13px;
  color: #9ca3af;
  max-width: 1000px;
  margin-left: auto;
  margin-right: auto;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top-color: white;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

.loading-spinner-small {
  display: inline-block;
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top-color: white;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* ==================== 过渡动画 ==================== */
.slide-down-enter-active,
.slide-down-leave-active {
  transition: all 0.3s ease;
  max-height: 400px;
}

.slide-down-enter-from,
.slide-down-leave-to {
  max-height: 0;
  opacity: 0;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* ==================== 响应式设计 ==================== */
@media (max-width: 1024px) {
  .chat-header {
    padding: 15px 20px;
  }
  
  .header-title {
    font-size: 20px;
  }
  
  .tools-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  }
  
  .messages-container {
    padding: 20px;
  }
}

@media (max-width: 768px) {
  .robot-icon {
    font-size: 32px;
  }
  
  .header-title {
    font-size: 18px;
  }
  
  .btn-text {
    display: none;
  }
  
  .header-btn {
    padding: 10px;
  }
  
  .tools-grid {
    grid-template-columns: 1fr;
  }
  
  .quick-questions {
    grid-template-columns: 1fr;
  }
  
  .message-content {
    max-width: 85%;
  }
  
  .welcome-icon {
    font-size: 60px;
  }
  
  .welcome-title {
    font-size: 24px;
  }
  
  .input-area {
    padding: 15px;
  }
  
  .input-wrapper {
    flex-direction: column;
    align-items: stretch;
  }
  
  .send-btn {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .messages-container {
    padding: 15px;
  }
  
  .message-avatar {
    width: 32px;
    height: 32px;
    font-size: 16px;
  }
  
  .message-text {
    padding: 12px 15px;
    font-size: 14px;
  }
}
</style>
